package top.smallway.lightbandassistant_app.network;

import android.util.Log;

import com.blankj.utilcode.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Search {
    /**
     * @param q 搜索的内容
     */
    public Search(String q, String minNps, String maxNps) {
        Search.q = q;
        Search.minNps = minNps;
        Search.maxNps = maxNps;
        Search.page.set(0);
    }

    private static String q;
    private static String minNps;
    private static String maxNps;

    private static AtomicInteger page = new AtomicInteger(0);
    private static final OkHttpClient httpClient = new OkHttpClient();

    /**
     * 该方法为第一次请求的构造器,Search.FirstGet()
     *
     * @return
     * @throws IOException
     */
    public synchronized String GetSongPage(int node) throws IOException {
        String url1 = "https://beatsaver.com/api/search/text/";
        String url2 = "https://yunos.smallway.top/";
        String url;
        if (node == 0) {
            url = url1;
        } else {
            url = url2;
        }

        url = url + page.getAndIncrement() + "?sortOrder=Relevance&q=" + q;
        if (!StringUtils.isEmpty(minNps)) {
            url = url + "&minNps=" + minNps;
        }

        if (!StringUtils.isEmpty(maxNps)) {
            url = url + "&maxNps=" + maxNps;
        }

        Request request = new Request.Builder().url(url).build();
        Log.i("url", url);
        Call call = httpClient.newCall(request);
        Response response = call.execute();
        return response.body().string();
    }

    /**
     * @param key
     * @return
     * @throws IOException
     */
    public static String getsong(String key, int node) throws IOException {
        String url1 = "https://beatsaver.com/api/maps/id/";
        String url2 = "https://key.smallway.top/";
        String url;
        if (node == 0) {
            url = url1;
        } else {
            url = url2;
        }

        Request request = new Request.Builder().url(url + key).build();
        Call call = httpClient.newCall(request);
        Response response = call.execute();
        return response.body().string();
    }
}
